<template>
  <el-dialog
    title="上传代码压缩包文件"
    :visible.sync="visible"
    width="600px"
    append-to-body
    :close-on-click-modal="false"
    @closed="handleClosed">

    <el-form ref="form" :model="form" label-width="80px">
      <el-form-item label="上传文件" prop="files">
        <el-upload
          ref="upload"
          :action="uploadUrl"
          :file-list="fileList"
          :headers="headers"
          :auto-upload="false"
          :limit="10"
          :on-exceed="handleExceed"
          :before-upload="beforeUpload"
          :on-change="handleChange"
          :on-success="handleSuccess"
          :on-error="handleError"
          :on-remove="handleRemove"
          multiple>
          <el-button size="small" type="primary">选择文件</el-button>
          <div slot="tip" class="el-upload__tip">
            支持多选，最多上传10个文件，单个文件不超过50MB
          </div>
        </el-upload>
      </el-form-item>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取 消</el-button>
      <el-button
        type="primary"
        @click="submitForm"
        :loading="uploading">
        {{ uploading ? '上传中...' : '确 定' }}
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getToken } from '@/utils/auth'
export default {
  data() {
    return {
      visible: false,
      uploading: false,
      fileList: [],
      headers: {
        Authorization: 'Bearer ' + getToken()
      },
      uploadUrl: process.env.VUE_APP_BASE_API + "/common/uploadCompress",
      form: {},
      // 新增：用于跟踪文件选择状态
      hasFilesSelected: false
    }
  },
  methods: {
    // 打开弹框
    open() {
      this.visible = true
    },

    // 文件超出限制
    handleExceed(files, fileList) {
      this.$message.warning(`最多上传10个文件，当前选择了${files.length}个文件`)
    },

    // 上传前校验
    beforeUpload(file) {
      const isLt50M = file.size / 1024 / 1024 < 50
      if (!isLt50M) {
        this.$message.error('单个文件大小不能超过50MB')
        return false
      }
      return true
    },

    // 新增：文件变化处理
    handleChange(file, fileList) {
      this.hasFilesSelected = fileList.length > 0
      this.fileList = fileList
    },

    // 提交表单
    submitForm() {
      // 方法1：通过ref获取上传文件列表（推荐）
      const uploadFiles = this.$refs.upload.uploadFiles

      // 方法2：通过内部状态判断
      // const hasFiles = this.hasFilesSelected || this.fileList.length > 0

      if (!uploadFiles || uploadFiles.length === 0) {
        this.$message.warning('请选择要上传的文件')
        return
      }

      this.uploading = true
      this.$refs.upload.submit()
    },

    // 上传成功处理
    handleSuccess(response, file, fileList) {
      if (response.code === 200) {
        this.$message.success('上传成功')
        this.visible = false
        this.$emit('success', response.data)
      } else {
        this.$message.error(response.msg || '上传失败')
      }
      this.uploading = false
    },

    // 上传失败处理
    handleError(err, file, fileList) {
      this.$message.error('上传失败：' + (err.message || '服务器错误'))
      this.uploading = false
    },

    // 文件移除处理
    handleRemove(file, fileList) {
      this.fileList = fileList
      this.hasFilesSelected = fileList.length > 0
    },

    // 弹框关闭处理
    handleClosed() {
      this.fileList = []
      this.hasFilesSelected = false
      this.uploading = false
      this.$refs.form.resetFields()
      // 清空上传组件文件列表
      if (this.$refs.upload) {
        this.$refs.upload.clearFiles()
      }
    }
  }
}
</script>

<style scoped>
.el-upload__tip {
  margin-top: 7px;
  color: #909399;
  font-size: 12px;
  line-height: 1.5;
}

.dialog-footer {
  text-align: right;
}
</style>
